﻿using System;
using System.Web;
using System.Web.Security;
using JSC.Portal.Data;
using JSC.Portal.Entities;
using JSC.Portal.Security;
using NHibernate;
using JSC.Core;
using JSC.Core.Data;
using JSC.Data.NHibernate;
using JSC.Portal.Services;

namespace JSC.Portal.Web.HttpModules
{
    public class AuthenticationModule : IHttpModule
    {
        private const int AUTHENTICATION_TIMEOUT = 20;

        public AuthenticationModule() { }

        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += new EventHandler(Context_AuthenticateRequest);
        }

        public void Dispose()
        {
            // Nothing here	
        }

        /// <summary>
        /// Try to authenticate the user.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool AuthenticateUser(string username, string password, bool persistLogin)
        {
            try
            {				
				IPortalUserService userSvc = new PortalUserService();
                string currentIp = HttpContext.Current.Request.UserHostAddress;
                
                PortalUser user;
                using(ITransaction t = NHibernateSession.Current.BeginTransaction())
                {
                    user = userSvc.Login(username, password, DateTime.Now, currentIp);
                    
                    /// Commit before redirection otherwise it will be rollbacked.
                    if (user != null)
                        t.Commit();
                    else
                        t.Rollback();
                }                
                
				if (user != null)
				{
					if (!user.IsActive)
					{
						throw new ApplicationException(Resources.Msg.TheAccountIsDisabled);
					}
					HttpContext.Current.User = new PortalPrincipal(user);
                    FormsAuthentication.SetAuthCookie(user.Name, persistLogin);
					
					return true;
					
				}
				else
				{
					return false;
				}
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format(Resources.Msg.UnableToLoginUserX + ex.Message, username), ex);
            }
        }

        /// <summary>
        /// Log out the current user.
        /// </summary>
        public static void Logout()
        {
            if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
            {
                FormsAuthentication.SignOut();
            }
        }

        private void Context_AuthenticateRequest(object sender, EventArgs e)
        {
			PortalApplication app = (PortalApplication)sender;
            if (app.Context.User != null && app.Context.User.Identity.IsAuthenticated)
            {
                if (string.IsNullOrEmpty(app.Context.User.Identity.Name))
                    return;
                int userId = Int32.Parse(app.Context.User.Identity.Name);
                IPortalUserService userSvc = new PortalUserService();
                PortalUser portalUser = userSvc.GetById(userId, false);
                portalUser.IsAuthenticated = true;
                app.Context.User = new PortalPrincipal(portalUser);
            }
        }
    }
}
